package com.appspot.didit.server;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.didit.client.statistic.ImageService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.appengine.repackaged.com.google.common.util.Base64DecoderException;

public class ImageServiceImpl extends RemoteServiceServlet implements ImageService {

        private static final long serialVersionUID = 506418524121350353L;

        public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    		resp.sendRedirect("/");
    		return;
    	}
        
        public String getImageToken(String base64image) {
                byte[] imageBytes;
                String token = null;
                try {
					imageBytes = Base64.decode(base64image);
					token = getMd5(base64image);
				} catch (Base64DecoderException e) {
					e.printStackTrace();
					imageBytes = null;
				}
                
                if (token == null) token = Math.round(Math.random()) + "";
                getThreadLocalRequest().getSession().setAttribute("img_" + token, imageBytes);
                return token;
        }

        private String getMd5(String base64image) {
                String token = null;
                try {
                        MessageDigest md5 = MessageDigest.getInstance("MD5");
                        md5.update(base64image.getBytes());
                        BigInteger hash = new BigInteger(1, md5.digest());
                        token = hash.toString(16);
                }
                catch (NoSuchAlgorithmException nsae) {}
                return token;
        }

}
